package com.lhkk.inventoryvehicle.common

import android.annotation.SuppressLint
import java.text.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*

/**
 * 时间处理工具
 */

object TimeUtil {
    private val dateFormat = object : ThreadLocal<SimpleDateFormat>() {
        @SuppressLint("ConstantLocale")
        override fun initialValue(): SimpleDateFormat {
            return SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        }
    }

    private val dateTimeFormat = object : ThreadLocal<SimpleDateFormat>() {
        @SuppressLint("ConstantLocale")
        override fun initialValue(): SimpleDateFormat {
            return SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        }
    }

    /**
     * 判断用户的设备时区是否为东八区（中国）
     * @return
     */
    val isInEasternEightZones: Boolean
        get() {
            return TimeZone.getDefault() === TimeZone.getTimeZone("GMT+08")
        }

    /**
     * 返回当前系统时间
     */
    fun getDataTime(format: String): String {
        val df = SimpleDateFormat(format, Locale.getDefault())
        return df.format(Date())
    }


    /**
     * 将字符串转位日期类型
     *
     * @param sdate
     * @return
     */
    fun toDate(sdate: String): Date? {
        return toDate(sdate, dateTimeFormat.get() ?: SimpleDateFormat("", Locale.CHINA))
    }

    fun toDate(sdate: String, dateFormater: SimpleDateFormat): Date? {
        try {
            return dateFormater.parse(sdate)
        } catch (e: ParseException) {
            return null
        }

    }

    /**
     * 以友好的方式显示时间
     *
     * @param dateTime
     * @return 友好的方式显示时间
     */
    fun friendlyTime(dateTime: Long): String {
        val date = Date(dateTime)
        return friendlyTime(date)
    }

    /**
     * 以友好的方式显示时间
     *
     * @param sdate
     * @return
     */
    fun friendlyTime(sdate: String): String {
        val time: Date?
        if (isInEasternEightZones) {
            time = toDate(sdate)
        } else {
            time =
                transformTime(toDate(sdate), TimeZone.getTimeZone("GMT+08"), TimeZone.getDefault())
        }
        if (time == null) {
            return "Unknown"
        }
        return friendlyTime(time)
    }

    private fun friendlyTime(time: Date): String {
        val ftime: String
        val cal = Calendar.getInstance()

        // 判断是否是同一天
        val curDate = dateFormat.get()?.format(cal.time)
        val paramDate = dateFormat.get()?.format(time)
        if (curDate == paramDate) {
            val hour = ((cal.timeInMillis - time.time) / 3600000).toInt()
            ftime = if (hour == 0) {
                Math.max((cal.timeInMillis - time.time) / 60000, 1).toString() + "分钟前"
            } else {
                hour.toString() + "小时前"
            }
            return ftime
        }

        val lt = time.time / 86400000
        val ct = cal.timeInMillis / 86400000
        val days = (ct - lt).toInt()
        ftime = if (days == 0) {
            val hour = ((cal.timeInMillis - time.time) / 3600000).toInt()
            if (hour == 0) {
                Math.max((cal.timeInMillis - time.time) / 60000, 1).toString() + "分钟前"
            } else {
                hour.toString() + "小时前"
            }
        } else if (days == 1) {
            "昨天 ${longTimeToStringTime(time.time, "HH:mm")}"
        } else if (days == 2) {
            "前天 ${longTimeToStringTime(time.time, "HH:mm")}"
        } else {
            longTimeToStringTime(time.time) //返回具体日期
        } //        } else if (days > 2 && days < 31) {
        //            ftime = days.toString() + "天前"
        //        } else if (days >= 31 && days <= 2 * 31) {
        //            ftime = "一个月前"
        //        } else if (days > 2 * 31 && days <= 3 * 31) {
        //            ftime = "2个月前"
        //        } else if (days > 3 * 31 && days <= 4 * 31) {
        //            ftime = "3个月前"
        //        } else {
        //            ftime = dateFormat.get()?.format(time) ?: ""
        //        }
        return ftime
    }

    /**
     * 根据不同时区，转换时间
     * @param date
     * @return
     */
    private fun transformTime(date: Date?, oldZone: TimeZone, newZone: TimeZone): Date? {
        var finalDate: Date? = null
        if (date != null) {
            val timeOffset = oldZone.getOffset(date.time) - newZone.getOffset(date.time)
            finalDate = Date(date.time - timeOffset)
        }
        return finalDate
    }


    /**
     * 时间戳转日期字符串
     * @return yyyy-MM-dd 格式
     */
    fun timestamp2DateFormat(timestamp: Long): String {
        return timestamp2String(timestamp, SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()))
    }

    /**
     * 时间戳转日期字符串
     * @return yyyy-MM-dd HH:mm格式
     */
    fun longTimeToStringTime(timestamp: Long): String {
        return timestamp2String(timestamp,
            SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()))
    }

    /**
     * 时间戳转日期字符串
     * @return yyyy-MM-dd HH:mm格式
     */
    fun longTimeToStringTime(timestamp: Long, pattern: String): String {
        return timestamp2String(timestamp, SimpleDateFormat(pattern, Locale.getDefault()))
    }

    /**
     * 时间戳转日期字符串
     * @return dateFormat
     */
    @JvmOverloads
    fun timestamp2String(timestamp: Long,
        dateFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
            Locale.getDefault())): String {
        try {
            return dateFormat.format(timestamp)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return ""
    }
}

